package cn.tk.engine.mr;

import cn.tk.model.pojo.mr.flow.ContextPair;
import cn.tk.model.pojo.mr.flow.FuncNodeDTO;
import cn.tk.model.pojo.mr.flow.FuncNodeParameter;
import cn.tk.service.mr.FuncNodeService;
import cn.tk.utils.EmptyUtil;
import cn.tk.utils.HttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by denglw on 2021/8/6.<br/>
 * Desc: 函数节点处理逻辑
 */
@Slf4j
@Component
public class FuncNodeDeal {

    @Autowired
    private FuncNodeService funcNodeService;

    /**
     * 函数节点解答.<br/>
     * @param funcNodeId 函数节点id
     * @param contextPairs 从会话上下文中获取的参数列表
     * @return 函数结果
     */
    public JSONObject funcCall(Long funcNodeId, List<ContextPair> contextPairs) {
        JSONObject bottomResult = new JSONObject();
        if (EmptyUtil.nullOrZero(funcNodeId)) {
            return bottomResult;
        }
        FuncNodeDTO node = funcNodeService.getFuncNode(funcNodeId);
        if (node == null) {
            return bottomResult;
        }
        String url = node.getFuncUrl();
        List<FuncNodeParameter> parameters = node.getFuncNodeParameters();
        // 组装入参
        List<NameValuePair> pairs = new ArrayList<>();
        for (FuncNodeParameter i : parameters) {
            String paramName = i.getName();
            Integer paramType = i.getParamType();
            if (!Objects.equals(paramType, 1)) {
                continue;
            }
            if (i.isVariableType()) {
                String enName = i.getVariableEnName();
                Optional<String> valueOption = contextPairs.stream().filter(j ->
                        Objects.equals(j.getName(), enName) && Objects.equals(j.getType(), 1)).findFirst().map(ContextPair::getValue);
                valueOption.ifPresent(s -> pairs.add(new BasicNameValuePair(paramName, s)));
            }
            if (i.isEntityType()) {
                String entityCode = i.getEntityCode();
                Optional<String> valueOption = contextPairs.stream().filter(j ->
                        Objects.equals(j.getName(), entityCode) && Objects.equals(j.getType(), 2)).findFirst().map(ContextPair::getValue);
                valueOption.ifPresent(s -> pairs.add(new BasicNameValuePair(paramName, s)));
            }
        }
        // 请求远程接口
        log.info("函数节点请求地址[{}],入参[{}].", url, pairs);
        String response = HttpClient.httpGet(url, pairs);
        if (EmptyUtil.blank(response)) {
            log.error("函数节点请求接口[{}]失败.", url);
            return bottomResult;
        }
        return JSON.parseObject(response);
    }

}
